package org.quxiao.hbase.test.singleAttrQuery;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySqlSingleAttrQueryTester implements SingleAttrQueryTester {

	private String driver = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://192.168.1.199:3306/";
	private String user = "root";
	private String password = "root";
	private Connection conn = null;
	private String dbName = "";
	private String tableName = "";
	private String key = "";
	private String value = "";
	
	public MySqlSingleAttrQueryTester(String url, String user, String password,
			String dbName, String tableName, String key, String value)
	{
		this.url = url;
		this.user = user;
		this.password = password;
		this.dbName = dbName;
		this.tableName = tableName;
		this.key = key;
		this.value = value;
	}
	
	private MySqlSingleAttrQueryTester() {}
	
	@Override
	public long queryTime() throws SingleAttrQueryException {
		// TODO Auto-generated method stub
		long queryTime = -1l;
		try
		{
			if ( ! connect() )
			{
				System.err.println("can't connect mysql");
				throw new SingleAttrQueryException();
			}
			Statement statement = conn.createStatement();
			String sql = "SELECT * FROM " + tableName + " WHERE " + key + " = \'" + value + "\'";
			
			queryTime = System.currentTimeMillis();
			ResultSet rs = statement.executeQuery(sql);	
			while ( rs.next() )
			{
//				++ count;
				//System.out.println("id: " + rs.getInt("id") + " value: " + rs.getString("type") + " vendor: " + rs.getString("vendor"));
//				int id = rs.getInt("id");
//				String type = rs.getString("level");
			}
			queryTime = System.currentTimeMillis() - queryTime;
//			System.out.println(count);
			statement.close();
			conn.close();
		}
		catch (SQLException sqlEx)
		{
			System.err.println(sqlEx);
			throw new SingleAttrQueryException();
		}
		return queryTime;
	}

	private boolean connect ()
	{
		try
		{
			Class.forName(driver);
			conn = DriverManager.getConnection(url + dbName, user, password);
		}
		catch (ClassNotFoundException ex)
		{
			System.err.println(ex);
			return false;
		}
		catch (SQLException ex)
		{
			System.err.println(ex);
			return false;
		}
		return true;
	}
	
	public String toString ()
	{
		return "MySQL single attribute query tester for table " + this.dbName;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
